<?php
namespace App\Http\Controllers\Store;

use App\Http\Requests\ChangeSaleRequest;
use App\Http\Requests\StoreGoodsAddTwoRequest;
use App\Http\Requests\StoreGoodsAddThreeRequest;
use App\Http\Requests\StoreGoodsAddFourRequest;
use App\Http\Requests\StoreGoodsDetailRequest;
use App\Http\Requests\StoreGoodsAddOneRequest;
use App\Http\Requests\StoreGoodsEditRequest;
use App\Http\Requests\CategoryAddRequest;
use App\Http\Requests\CategoryDelRequest;
use App\Models\ShopCategory;
use App\Models\ShopGoods;
use App\Models\ShopGoodsImage;
use App\Http\Requests\BasicRequest;
use Illuminate\Support\Facades\DB;
class GoodsController extends CommonController {

    private $goods_type;
    public function __construct()
    {
        parent::__construct();
        if($this->store->store_type==1){
            $this->goods_type = 3;
        }else{
            $this->goods_type = 4;
        }
    }
    //图片类型
    const HEAD_IMG = 1;
    const DETAIL_IMG = 2;

    //商品管理首页
    public function index(BasicRequest $request){
        $return['sale'] = ShopGoods::where(['store_id'=>$this->store_id,'status'=>1])->where('stock','>','0')->count();

        $return['wait_sale'] = ShopGoods::where(['store_id'=>$this->store_id])->where(function($query){
            $query->where('status','!=',1)->orWhere('stock','=','0');
        })->count();
		$return['all'] = ShopGoods::where(['store_id'=>$this->store_id])->count();
		$return['status_list']=array(
		    '0'=>['id'=>'0','name'=>'全部'],
		    '1'=>['id'=>'1','name'=>'上架'],
		    '2'=>['id'=>'2','name'=>'下架'],
		    '3'=>['id'=>'3','name'=>'回收站']
        );
        return json_success('OK',$return);
    }
    //商品列表
    public function goods_list(BasicRequest $request){
        $status = $request->input('status',0);
        $return['goods_list']=ShopGoods::where(['store_id'=>$this->store_id,'is_del'=>0])
            ->Field()
            ->when($status,function($query) use($status){
                if($status>0) {
                    $query->where(['status' => $status]);
                }
            })->orderBy('updated_at','desc')->pages()->each(function ($v,$k){
                $v->cate_name = ShopCategory::where(['id'=>$v->cate_id])->value('cate_name');
                unset($v->cate_id);
            });

        return json_success('OK',$return);
    }
    //更改上架状态
    public function change_sale(ChangeSaleRequest $request){
        $status=$request->input('status');
        $goods_id=$request->input('goods_id');
        if(in_array($status,['1','2','3'])) {
            $return = ShopGoods::where(['store_id' => $this->store_id, 'id' => $goods_id])->update(['status' => $status]);
            if ($return) {
                return json_success('OK', $return);
            } else {
                return json_error('操作失败，请重试');
            }
        }else return json_error('操作失败，请重试');
    }
    //商品详情
    public function goods_detail(StoreGoodsDetailRequest $request){
        $goods_id = $request->input('goods_id');
        $goods_type = $this->goods_type;
        $goods_detail=ShopGoods::getGoodsDetail($goods_id);
        $goods_detail->head_image=DB::table('shop_goods_img')->select('img_url')->where(['goods_type'=>$goods_type,'img_type'=>self::HEAD_IMG,'goods_id'=>$goods_id])->orderBy('img_serial','asc')->get()->pluck('img_url');
        $goods_detail->detail_image=DB::table('shop_goods_img')->select('img_url')->where(['goods_type'=>$goods_type,'img_type'=>self::DETAIL_IMG,'goods_id'=>$goods_id])->orderBy('img_serial','asc')->get()->pluck('img_url');
        $goods_sale = DB::table('shop_goods_sale')->select('sale_num','jsale_num')->where(['goods_type'=>$goods_type,'goods_id'=>$goods_id])->first();
        if($goods_sale) { $goods_detail->sale_num = $goods_sale->sale_num + $goods_sale->jsale_num; }else{$goods_detail->sale_num = 0; }//销售数量
        return json_success('OK',$goods_detail);
    }
    //获取商品分组列表
    public function category(){

        $return = ShopCategory::LeftJoin('shop_goods','shop_goods.cate_id','=','shop_category.id')
            ->where(['shop_category.store_id'=>$this->store_id,'shop_category.is_del'=>0])
            ->select('shop_category.id as cate_id','shop_category.cate_name',DB::raw('COUNT(shop_goods.id) as goods_num'))
            ->groupBy('shop_category.id')
            ->orderBy('shop_category.sort','desc')
            ->pages();
        $return->prepend(['cate_id' => 0, 'cate_name' => '默认分组','goods_num'=>ShopGoods::where(['cate_id'=>0,'store_id'=>$this->store_id])->count()]);
        return json_success('OK',$return);
    }

    //新增商家分组
    public function category_edit(CategoryAddRequest $request){
        $cate_id = $request->input('cate_id');
        $cate_name = $request->input('cate_name');
        $sort = $request->input('sort',1);

        $check = ShopCategory::where(['store_id'=>$this->store_id,'cate_name'=>$cate_name,'is_del'=>0])
            ->when($cate_id,function($query) use ($cate_id){
                $query->where('id','!=',$cate_id);
            })->first();
        if($check){
            return json_error('您已有同名分类');
        }
        $input=array();
        $input['cate_name'] = $cate_name;
        $input['cate_detail'] = $request->input('cate_detail');
        $input['store_id'] = $this->store_id;
        $input['sort'] = $sort;
        if($cate_id){
            $return = ShopCategory::where('id','=',$cate_id)->update($input);
        }else{
            $return = ShopCategory::create($input);
        }
        if($return){
            return json_success('OK',$return);
        }else{
            return json_error('操作失败，请稍后重试或联系客服');
        }
    }
    //删除商家分类
    public function category_del(CategoryDelRequest $request){
        $cate_id = $request->input('cate_id');
        //删除分类
        ShopCategory::where(['id'=>$cate_id,'store_id'=>$this->store_id])->delete();
        //将商品移入默认分类
        ShopGoods::where(['id'=>$cate_id,'store_id'=>$this->store_id])->update(['cate_id'=>0]);
        return json_success(' OK');
    }

    public function goods_edit(StoreGoodsEditRequest $request){
        $goods_id = $request->input('goods_id');
        $return['goods_info']=ShopGoods::where(['store_id'=>$this->store_id,'id'=>$goods_id])->first();
        $return['goods_info']->cate_name = ShopCategory::where(['id'=>$return['goods_info']->cate_id])->value('cate_name');
        $return['head_image'] = ShopGoodsImage::where(['goods_id'=>$goods_id,'goods_type'=>$this->goods_type,'img_type'=>self::HEAD_IMG])->get();
        $return['detail_image'] = ShopGoodsImage::where(['goods_id'=>$goods_id,'goods_type'=>$this->goods_type,'img_type'=>self::DETAIL_IMG])->get();
        return json_success('OK',$return);
    }
    //编辑商品基础信息
    public function goods_edit_one(StoreGoodsAddOneRequest $request){
        $goods_id = $request->input('goods_id');
        $input=array();
        $input['goods_name'] = $request->goods_name;
        $input['summary'] = $request->summary;
        //检查是否重名
        $check = ShopGoods::where(['store_id'=>$this->store_id,'goods_name'=>$input['goods_name']])
            ->when($goods_id,function($query) use ($goods_id){
                $query->where('id','!=',$goods_id);
            })->first();
        if($check){
            return json_error('您已有一件相同名字得商品');
        }
        $input['goods_type'] = $this->goods_type;

        if(!$goods_id){
            $input['status'] = 3;
        }
        $input['cate_id'] = $request->cate_id;
        $input['stock'] = $request->stock;
        $input['store_id'] = $this->store_id;
        $return = ShopGoods::updateOrCreate(['id'=>$goods_id],$input);
        if($return){
            return json_success('OK',$return);
        }else{
            return json_error('操作失败，请稍后重试或联系客服');
        }
    }
    //编辑商品图文信息
    public function goods_edit_two(StoreGoodsAddTwoRequest $request){
        $goods_id = $request->input('goods_id');
        $goods_image = $request->input('goods_image');
        $head_image = $request->input('head_image');
        $detail_image = $request->input('detail_image');
        $return=DB::transaction(function () use($goods_image,$head_image,$detail_image,$goods_id) {

            $goods_type = $this->goods_type;
            ShopGoods::where(['id' => $goods_id])->update(['goods_image'=>$goods_image]);
            $head_image = explode('|',$head_image);
            $detail_image = explode('|',$detail_image);
            ShopGoodsImage::where(['goods_id'=>$goods_id,'goods_type'=>$goods_type])->delete();
            foreach ($head_image as $key=>$val) {
                ShopGoodsImage::create([
                    'goods_id'=>$goods_id,
                    'goods_type'=>$goods_type,
                    'img_url'=>$val,
                    'img_type'=>self::HEAD_IMG,
                ]);
            }
            foreach ($detail_image as $key=>$val) {
                ShopGoodsImage::create([
                    'goods_id'=>$goods_id,
                    'goods_type'=>$goods_type,
                    'img_url'=>$val,
                    'img_type'=>self::DETAIL_IMG,
                ]);
            }
            return true;

        });
        if($return){
            return json_success('OK',['goods_id'=>$goods_id]);
        }else{
            return json_error('操作失败，请稍后重试或联系客服');
        }
    }

    //编辑商品价格信息
    public function goods_edit_three(StoreGoodsAddThreeRequest $request){
        $goods_id = $request->input('goods_id');
        $input['goods_price'] = $request->input('goods_price');
        $input['market_price'] = $request->input('market_price');
        if($input['goods_price']==0){
            return json_error('商品金额必须大于0');
        }
        $return = ShopGoods::where(['id'=>$goods_id])->update($input);
        if($return){
            return json_success('OK',$return);
        }else{
            return json_error('操作失败，请稍后重试或联系客服');
        }
    }

    //编写其他信息
    public function goods_edit_four(StoreGoodsAddFourRequest $request){

        $goods_id = $request->input('goods_id');
        $input['start_type'] = $request->input('start_type');
        $input['end_type'] = $request->input('end_type');
        $input['start_time'] = $request->input('start_time');
        $input['end_time'] = $request->input('end_time');
        if($input['start_type']==1){
            //立即上架
            $input['status'] = 1;
        }else {
            //选择上架时间
            if($input['end_type']==1){
                //售完下架
                if (time() > strtotime($input['start_time'])){
                    $input['status']=1;
                }else{
                    $input['status']=2;
                }
            }else if (time() < strtotime($input['end_time'])) {
                //固定下架时间
                $input['status'] = 1;
            } else {
                $input['status'] = 2;
            }
        }
        $return = ShopGoods::where(['id'=>$goods_id])->update($input);
        if($return){
            return json_success('OK',$return);
        }else{
            return json_error('操作失败，请稍后重试或联系客服');
        }
    }
}